import dayjs from "dayjs";
import { pathToRegexp } from "path-to-regexp";
import relativeTime from "dayjs/plugin/relativeTime";
import type { Route, IterationRouteHandler } from "@/typings/route";

dayjs.extend(relativeTime);

/**
 * 迭代routes
 * */
export function iterationRoutes(
  routes: Route[],
  handler: IterationRouteHandler
) {
  function iteration(items: Route[]) {
    items.forEach(iterationRoute);
  }
  function iterationRoute(route: Route) {
    handler(route);
    const childs = route.children;
    if (childs?.length) iteration(childs);
  }
  iteration(routes);
  return routes;
}

/**
 * 路由匹配
*/
export const matchRoutes = (routes: Route[], pathname: string) => {
  const matches: Route[] = [];
  iterationRoutes(routes, (route) => {
    const path = route.path;
    if (path && !route.redirect) {
      const regexp = pathToRegexp(path, [], { end: false });
      if (regexp.test(pathname)) matches.push(route);
    }
  });
  return matches;
};


export const jsonFix = (str: string) => {
  return eval(`(${str})`);
}